﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using TeacherLoad.Classes;
using System.ComponentModel;
using System.Text.RegularExpressions;

namespace TeacherLoad.Windows
{
    /// <summary>
    /// Логика взаимодействия для UchebPlanList.xaml
    /// </summary>
    public partial class UchebPlanList : Window
    {
        private static readonly List<Specialization> _emptySpecList = new List<Specialization>()
        {
            new Specialization()
        };
        private List<AcademicItem> _itemList = new List<AcademicItem>();
        private readonly List<AcademicItem> _emptyItemList = new List<AcademicItem>()
        {
            new AcademicItem()
        };
        private int _totalHours = 0;
        private Regex regex = new Regex("[^0-9]");
        private int _id = 0;
        // Конструктор
        public UchebPlanList()
        {
            InitializeComponent();
            cbSpec.DataContext = LoadSpec();
            cbSpec.Items.SortDescriptions.Add(new SortDescription("Code", ListSortDirection.Ascending));
            cbItem.DataContext = LoadItems();
            cbItem.Items.SortDescriptions.Add(new SortDescription("ItemName", ListSortDirection.Ascending));
            txTotal.Text = _totalHours.ToString();
        }

        private List<Specialization> LoadSpec()
        {
            DataTable dt = SendToServer.GetSpec();
            List<Specialization> spec = new List<Specialization>();
            if (dt.Rows.Count != 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Specialization sp = new Specialization(
                        Convert.ToInt32(row[0]),
                        row[1].ToString(),
                        row[2].ToString(),
                        row[3].ToString());
                    spec.Add(sp);
                }
                //ChangeRow.IsEnabled = true;
            }
            else
            {
                spec = _emptySpecList;
                //ChangeRow.IsEnabled = false;
            }
            return spec;
        }

        private List<AcademicItem> LoadItems()
        {
            DataTable dt = SendToServer.GetItems();
            _itemList = new List<AcademicItem>();
            if (dt.Rows.Count != 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    AcademicItem item = new AcademicItem(
                        Convert.ToInt32(row[0]),
                        row[1].ToString());
                    _itemList.Add(item);
                }
            }
            else
            {
                _itemList = _emptyItemList;
            }
            return _itemList;
        }

        private void cbSpec_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ClearEdit.Visibility = Visibility.Visible;
        }

        private void btnAddPlan_Click(object sender, RoutedEventArgs e)
        {
            int year = DateTime.Now.Year + 1;
            if (cbSpec.SelectedIndex != -1 && txYear.Text.Length > 0)
            {
                int y = Convert.ToInt32(txYear.Text);
                int idUchPlan = Convert.ToInt32(cbSpec.SelectedValue);
                if (y >= 2000 && y <= year)
                {
                    UchPlan plan = new UchPlan(_id, y, idUchPlan);
                    if (SendToServer.AddUchPlan(plan))
                    {
                        cbSpec.SelectedIndex = -1;
                        txYear.Clear();
                        ClearEdit.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        MessageError();
                    }    
                }
                else
                {
                    MessageError();
                }
            }
        }

        // Сообщение об ошибке записи
        private void MessageError()
        {
            MessageBox.Show("Ошибка записи", "Неудача",
                        MessageBoxButton.OK, MessageBoxImage.Error);
        }
        private void listPlan_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ChangeRow_Click(object sender, RoutedEventArgs e)
        {

        }

        private void txYear_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (txYear.Text.Length < 4)
            {
                e.Handled = regex.IsMatch(e.Text);
            }
            else
            {
                e.Handled = true;
            }
        }

        private void btnCancelEditPlan_Click(object sender, RoutedEventArgs e)
        {

        }

        private void ClearEdit_Click(object sender, RoutedEventArgs e)
        {
            cbSpec.SelectedIndex = -1;
            txYear.Clear();
            ClearEdit.Visibility = Visibility.Collapsed;
        }

        private void txYear_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (txYear.Text.Length != 0)
            {
                ClearEdit.Visibility = Visibility.Visible;
            }
            else if (cbSpec.SelectedIndex == -1)
            {
                ClearEdit.Visibility = Visibility.Collapsed;
            }
        }

        private void btnAddItem_Click(object sender, RoutedEventArgs e)
        {
            Window window = new AcadItems();
            window.ShowDialog();
        }

        private void Window_GotFocus(object sender, RoutedEventArgs e)
        {
            //cbItem.DataContext = LoadItems();     Подумать
        }

        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            string message = "Очистить поля ввода?";
            string headerMessage = "Подтвердите действие";
            MessageBoxResult result = MessageBox.Show(message, headerMessage,
                MessageBoxButton.OKCancel, MessageBoxImage.Question);

            if (result == MessageBoxResult.OK)
            {
                ClearTextBox();
            }
        }

        private void ClearTextBox()
        {
            txIndex.Clear();
            cbItem.SelectedIndex = -1;
            cbItem.Text = "";
            txZach.Clear();
            txDZach.Clear();
            txEkz.Clear();
            IsPractice.IsChecked = false;
            txTeor.Clear();
            txPract.Clear();
            txConsult.Clear();
            txAttest.Clear();
            txSelf.Clear();
            txTotal.Clear();
            sem1.Clear();
            sem2.Clear();
            sem3.Clear();
            sem4.Clear();
            sem5.Clear();
            sem6.Clear();
            sem7.Clear();
            sem8.Clear();
        }

        private void hours_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            e.Handled = regex.IsMatch(e.Text);
        }
    }
}
